package com.team.register.utils;
import com.team.register.pojo.Admin;
import com.team.register.pojo.BaseUser;

import java.io.*;

/**
 * @Program: clps-learning
 * @Description:
 * @author: Cooper
 */
public class FileUtil {


    public static Boolean write(BaseUser baseUser) {
        Boolean isSuccess = false;
        // resources路径
        // String filePath = FileUtil.class.getClassLoader().getResource("").getPath() + baseUser.getUsername() + ".txt";
        String filePath = baseUser.getUsername() + ".txt";

        // 序列化user对象并写出txt文件
        try (
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(baseUser);
            oos.flush();
            isSuccess = true;
        }catch (IOException e){
            e.printStackTrace();
        }
        return isSuccess;
    }



    /**
     * @deprecated:  输入用户名， 反序列化读取用户名.txt文件，返回BaseUser对象
     * @param username: 用户名
     * @return: com.team.register.pojo.BaseUser
     * @exception/throws:
     * @author: Cooper
     */

    public static BaseUser read(String username)  {
        BaseUser baseUser = null;
        // resources路径
        //String filePath = FileUtil.class.getClassLoader().getResource("").getPath() + username + ".txt";
        String filePath = username + ".txt";

        try(
            // 反序列化
            FileInputStream fis = new FileInputStream(new File(filePath));
            ObjectInputStream ois = new ObjectInputStream(fis);
        ){
            baseUser = (BaseUser) ois.readObject();

        }catch (Exception e){
            e.printStackTrace();
        }
        return baseUser;
    }

    public static void main(String[] args) {
        // 注册
        BaseUser admin = new Admin("admin","admin");
        FileUtil.write(admin);
        // 登录
        BaseUser adminL = FileUtil.read("admin");
        System.out.println(adminL.toString());
    }

}
